package com.test.logindemo;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.SessionAware;

import java.util.Map;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/9/8 15:07
 */
public class UserAction implements SessionAware, ApplicationAware {

    private Map<String, Object> sessionMap;
    private Map<String, Object> applicationMap;
    private String username;

    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * 登陆
     *
     * @return
     */
    @SuppressWarnings("unckecked")
    public String login() {
        // 把用户信息存入session中
        // 1.获取sesison，通过实现SessionAware接口
        // 2.获取登陆信息: 通过在Action中添加setter方法
        sessionMap.put("username", username);
        // 3.把用户信息存入session中

        // 在线人数加1
        // 1.获取当前的在线人数
        // 2.在线人数加1后存入application中
        if (applicationMap.containsKey("userNum")) {
            Object n = applicationMap.get("userNum");
            Integer num = (Integer) n;
            num++;
            applicationMap.put("userNum", num);
        } else {
            applicationMap.put("userNum", 1);
        }

        return "login-success";
    }

    /**
     * 注销
     *
     * @return
     */
    public String logout() {
        //使当前session失效
        ((SessionMap<String, Object>) sessionMap).invalidate();
        //当前在线人数减一
        if (applicationMap.containsKey("userNum")) {
            Object n = applicationMap.get("userNum");
            Integer num = (Integer) n;
            if (num > 0) {
                num--;
            }
            applicationMap.put("userNum", num);
        } else {
            applicationMap.put("userNum", 0);
        }
        return "logout-success";
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.sessionMap = session;
    }

    @Override
    public void setApplication(Map<String, Object> application) {
        this.applicationMap = application;
    }
}
